package controller

import (
	"jtvss/api/system/dto"
	"jtvss/api/system/model"
	"jtvss/configs"
	"jtvss/middleware"
	"jtvss/pkg/ctx"
	"jtvss/pkg/orm"
	"jtvss/util"
	"os"
	"path"
	"path/filepath"

	"github.com/gin-gonic/gin"
)

// File
type File struct {
}

// ListHandler 列表
func (o *File) ListHandler(c *gin.Context) {
	var p dto.Where
	if err := c.ShouldBind(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	var data []model.File
	total, _ := p.DbModelWhere(&model.File{}).Find(&data)
	ctx.JSONWriteTotal(total, data, c)
}

// GetHandler 查询详细
func (o *File) GetHandler(c *gin.Context) {
	util.QueryByID(&model.File{}, c)
}

// AddHandler 新增
func (o *File) AddHandler(c *gin.Context) {
	var p model.File
	//获取参数
	if err := c.ShouldBind(&p.FileOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbCreate(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// UpdateHandler 修改
func (o *File) UpdateHandler(c *gin.Context) {
	var p model.File
	//获取参数
	if err := c.ShouldBind(&p.FileOpt); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	if err := orm.DbUpdateModel(&p); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

// DeleteHandler 删除
func (o *File) DeleteHandler(c *gin.Context) {
	util.Deletes(&model.File{}, c)
}

func (o *File) UploadHandler(c *gin.Context) {
	fileHead, err := c.FormFile("file")
	if err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	filename := configs.Public.Abs("files", fileHead.Filename)
	os.MkdirAll(filepath.Dir(filename), os.ModePerm)
	if err := c.SaveUploadedFile(fileHead, filename); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	tok := middleware.UserToken(c)
	data := &model.File{
		FileOpt: model.FileOpt{
			Name: fileHead.Filename,
			Path: filename,
			Size: fileHead.Size,
			Desc: fileHead.Filename,
			Type: path.Ext(fileHead.Filename),
		},
		CreatedBy: tok.UserName,
	}
	if err := orm.DbCreate(data); err != nil {
		ctx.JSONWriteError(err, c)
		return
	}
	ctx.JSONWriteData(nil, c)
}

func (o File) Routers(r *gin.RouterGroup) {
	r.GET("/list", o.ListHandler)
	r.GET("/:id", o.GetHandler)
	r.POST("", o.AddHandler)
	r.PUT("", o.UpdateHandler)
	r.DELETE("/:id", o.DeleteHandler)
	r.POST("/upload", o.UploadHandler)
}
